/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  LayoutAddActivity.java   
 * @Package com.jiyi.activity.owner   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-12 上午10:40:41   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.SinglePicActivity;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.owner.BuildEquipBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.BuildListEvent;
import com.jiyi.inteface.WebApi;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.CameraUtils;
import com.swift.utils.GlideUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @ClassName: LayoutAddActivity
 * @Description:TODO(新增楼层)
 * @author: HYM
 * @date: 2017-9-12 上午10:40:41
 * 
 */
public class LayoutAddActivity extends SinglePicActivity {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.state_build)
	Spinner state_build;

	@BindView(R.id.etLayout)
	EditText etLayout;
	@BindView(R.id.etRatio)
	EditText etRatio;
	@BindView(R.id.etLayoutRemark)
	EditText etLayoutRemark;
	@BindView(R.id.tvUpload)
	TextView tvUpload;
	@BindView(R.id.llContent)
	LinearLayout llContent;
	@BindView(R.id.ivPic)
	ImageView ivPic;

	// 进度条
	Dialog dialog;
	// 大楼列表适配器
	CommonAdapter<BuildEquipBean> stateDlAdapter;
	// 大楼列表数据源
	List<BuildEquipBean> dlDataList = new ArrayList<BuildEquipBean>();

	// 大楼ID,楼层ID,公司ID
	private String companyId, buildId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_layout_add);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		getIntentData();
		setTop();
		setViewStatus();
		setAdapter();
		getDlData();
	}

	private void getIntentData() {
		companyId = getIntent().getStringExtra("companyId");
		buildId = getIntent().getStringExtra("buildId");
	}

	private void setTop() {
		tvTitle.setText("新增楼层");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("取消");
	}

	/**
	 * @author: HYM
	 * @Title: setAdapter
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-9-15
	 */
	private void setAdapter() {
		stateDlAdapter = new CommonAdapter<BuildEquipBean>(this, dlDataList,
				R.layout.item_equipment_repair_state) {

			@Override
			public void convert(ViewHolder holder, BuildEquipBean t) {
				holder.setText(R.id.state_name, t.getBuilding());
			}
		};
		state_build.setAdapter(stateDlAdapter);
		state_build.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				BuildEquipBean et = (BuildEquipBean) parent.getAdapter()
						.getItem(position);
				state_build.setTag(R.id.tag_view_select_value, et.getId());
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	private void setViewStatus() {
		// 设置必填项检测提示
		state_build.setTag(R.id.tag_view_empty, "大楼不能为空");
		etLayout.setTag(R.id.tag_view_empty, "楼层不能为空");
		etRatio.setTag(R.id.tag_view_empty, "距离比例不能为空");
	}

	@OnClick({ R.id.tvBack, R.id.tvSearch, R.id.tvPost, R.id.tvUpload })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
		case R.id.tvSearch:
			finish();
			break;
		case R.id.tvPost:
			// 执行新增操作
			if(TextUtils.isEmpty(filePath))
			{
				ToastUtil.getInstances().showMsg("请选择一张平面图");
				return;
			}
			if (CheckUtil.checkView(state_build,etLayout,etRatio)) {
				doPost();
			}
			break;
		case R.id.tvUpload:
			mPickPopView.showPopWindow();
			break;
		default:
			break;
		}
	}

	public Context getContext() {
		return this;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == CAMARE_CODE && resultCode == RESULT_OK) {
			try {
				GlideUtil.loadIntoUseFitWidth(getContext(), new File(filePath),
						ivPic);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (requestCode == CHOOSE_PICTURE) {
			if (resultCode == RESULT_OK) {
				if (data != null) {
					Uri temp = data.getData();
					filePath = CameraUtils.getImageAbsolutePath(this, temp);
					GlideUtil.loadIntoUseFitWidth(getContext(), new File(
							filePath), ivPic);

				}

			}
		}
	}

	private void getDlData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", companyId);

		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_OWNER_EQUIP_LIST, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<BuildEquipBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<BuildEquipBean>>() {
												}.getType());
								if (temp == null || temp.size() <= 0) {
									ToastUtil.getInstances().showMsg("请先新增大楼");
								} else {
									dlDataList.addAll(temp);
									stateDlAdapter.notifyDataSetChanged();

									// 选中当前的大楼
									for (int i = 0; i < dlDataList.size(); i++) {
										BuildEquipBean buildEquipBean = dlDataList
												.get(i);
										if (buildEquipBean.getId().equals(
												buildId)) {
											state_build.setSelection(i);
											break;
										}
									}
								}
							} else {
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}

					}

					@Override
					public void stringError(VolleyError error) {
					}
				});
	}
	
	void doPost()
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put(AppConfig.COMPANY_ID_KEY, companyId);
		params.put(
				"build_id",
				new Gson().fromJson(state_build.getSelectedItem().toString(),
						BuildEquipBean.class).getId());
		params.put("floor_no", etLayout.getText().toString());
		params.put("describe", etLayoutRemark.getText().toString());
		params.put("ratio", etRatio.getText().toString());
		
		PostFormBuilder postForm = OkHttpUtils.post().url(WebApi.MAINTENANCE_OWNER_FLOOR_ADD);
		postForm.params(params);
		if (!TextUtils.isEmpty(filePath)) {
			File file = new File(filePath);
			postForm.addFile("map", "shoot_file.jpg", file);
		}

		dialog = showDialog(dialog);
		postForm.build().execute(new StringCallback() {

			@Override
			public void onError(Call arg0, Exception exception, int arg2) {
				hideDialog(dialog);
				ToastUtil.getInstances().showMsg(exception.getMessage());
			}

			@Override
			public void onResponse(String result, int arg1) {
				try {
					JSONObject obj = new JSONObject(result);
					String status = obj.getString("status");
					String info = obj.getString("info");
					if (status.equals("200")) {
						ToastUtil.getInstances().showMsg(info);
						EventBus.getDefault().post(new BuildListEvent());
						finish();
					} 
					else if (status.equals("404") && info.contains("尚未登录")) {
						ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
						//清除环信登录
						UserHelp.getInstance().clearUser(AppBase.Context, true);
						return;
					}
					else {
						ToastUtil.getInstances().showMsg(info);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					hideDialog(dialog);
				}
			}
		});
	}
}
